package net.lz1998.pbbot.plugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lz1998.pbbot.bot.Bot;
import net.lz1998.pbbot.bot.BotPlugin;
import net.lz1998.pbbot.constant.BannedConstant;
import net.lz1998.pbbot.constant.GroupInfoConstant;
import net.lz1998.pbbot.constant.TitleConstant;
import net.lz1998.pbbot.utils.HttpsRequestUtils;
import net.lz1998.pbbot.utils.HttpRequestUtils;
import net.lz1998.pbbot.utils.Msg;
import onebot.OnebotApi;
import onebot.OnebotEvent;
import onebot.OnebotEvent.FriendRecallNoticeEvent;
import onebot.OnebotEvent.GroupRecallNoticeEvent;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@Component
public class LogPlugin extends BotPlugin {
	@Override
	public int onPrivateMessage(@NotNull Bot bot, @NotNull OnebotEvent.PrivateMessageEvent event) {
		//log.info("收到私聊消息 QQ：{} 内容：{}", event.getUserId(), event.getRawMessage());
		return MESSAGE_IGNORE;
	}

	@Override
	public int onGroupMessage(@NotNull Bot bot, @NotNull OnebotEvent.GroupMessageEvent event) {
		// 这里展示了RawMessage的用法（纯String）
		long groupId = event.getGroupId();
		long userId = event.getUserId();
		String msg = event.getRawMessage().trim();
		String[] arr = msg.split(" ");
		if(arr[0].equals(TitleConstant.DIANGE)&&arr.length==2){

			String muisc = arr[1];

			JSONObject jsonObject=null;
			//请求网易云音乐接口
			String wyyResult = HttpRequestUtils.doGet("https://autumnfish.cn/cloudsearch?keywords="+muisc+"&limit=1");
			jsonObject = JSON.parseObject(wyyResult);
			if (jsonObject.getInteger("code") != 200) {
				bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(GroupInfoConstant.INFO), true);
				return MESSAGE_IGNORE;
			}
			if(CollectionUtils.isEmpty(jsonObject.getJSONObject("result"))){
				bot.sendGroupMsg(groupId, Msg.builder().at(userId).text("歌曲["+muisc+"]你自己创作吧,反正我是搜不到.."), true);
				return MESSAGE_IGNORE;
			}

			//歌曲id
			String id = jsonObject.getJSONObject("result").getJSONArray("songs").getJSONObject(0).getString("id");
			//歌曲名称
			String muiscName = jsonObject.getJSONObject("result").getJSONArray("songs").getJSONObject(0).getString("name");
			//歌手名称
			String name = jsonObject.getJSONObject("result").getJSONArray("songs").getJSONObject(0)
					.getJSONArray("ar")
					.getJSONObject(0)
					.getString("name");
			//歌曲图片
			String picUrl = jsonObject.getJSONObject("result").getJSONArray("songs").getJSONObject(0)
					.getJSONObject("al")
					.getString("picUrl");

			//请求qq音乐接口
			//String qqResult = HttpRequestUtils.doGet("https://api.zsfmyz.top/music/list?p=1&n=1&w="+muisc);
			String qqResult = null;
			try {
				qqResult = HttpsRequestUtils.httpsRequest("https://api.zsfmyz.top/music/list?p=1&n=1&w="+ URLEncoder.encode(muisc,"UTF-8"),"GET",null);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			jsonObject = JSON.parseObject(qqResult);
			if (jsonObject.getInteger("code") != 0) {
				bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(GroupInfoConstant.INFO), true);
				return MESSAGE_IGNORE;
			}

			JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
			if (CollectionUtils.isEmpty(jsonArray)) {
				bot.sendGroupMsg(groupId, Msg.builder().at(userId).text("歌曲["+muisc+"]你自己创作吧,反正我是搜不到.."), true);
				return MESSAGE_IGNORE;
			}

			String songmId = jsonObject.getJSONObject("data").getJSONArray("list").getJSONObject(0).getString("songmid");

			String info="<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n" +
					"<msg serviceID=\"2\" templateID=\"1\" action=\"web\" brief=\"[分享] "+muiscName+"\" sourceMsgId=\"0\"\n" +
					"     url=\"https://i.y.qq.com/v8/playsong.html?_wv=1&amp;songmid="+songmId+"&amp;souce=qqshare&amp;source=qqshare&amp;ADTAG=qqshare\"\n" +
					"     flag=\"3\" adverSign=\"0\" multiMsgFlag=\"0\">\n" +
					"    <item layout=\"2\">\n" +
					"        <audio cover=\""+picUrl+"\"\n" +
					"               src=\"https://music.163.com/song/media/outer/url?id="+id+".mp3\"/>\n" +
					"        <title>"+muiscName+"</title>\n" +
					"        <summary>"+name+"</summary>\n" +
					"    </item>\n" +
					"    <source name=\"QQ音乐\" icon=\"https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png?date=20190804\"\n" +
					"            url=\"http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856\" action=\"app\"\n" +
					"            a_actionData=\"com.tencent.qqmusic\" i_actionData=\"tencent1101079856://\" appid=\"1101079856\"/>\n" +
					"</msg>";
			bot.sendGroupMsg(groupId,Msg.builder().xml(0, info), false);
		}
		return MESSAGE_IGNORE;
	}

	@Override
	public int onFriendRecallNotice(Bot bot, FriendRecallNoticeEvent event) {
		long userId = event.getUserId();
		int messageId = event.getMessageId();
		String rawMessage = bot.getMsg(messageId).getRawMessage();
		bot.sendPrivateMsg(userId, "用户["+userId+"]刚刚偷偷撤回的消息内容是:"+rawMessage, false);
		return MESSAGE_IGNORE;
	}

	@Override
	public int onGroupRecallNotice(Bot bot, GroupRecallNoticeEvent event) {
		long userId = event.getUserId();
		long groupId = event.getGroupId();
		int messageId = event.getMessageId();
		OnebotApi.GetStrangerInfoResp strangerInfo =  bot.getStrangerInfo(userId);
		OnebotApi.GetGroupMemberInfoResp groupMemberInfo = bot.getGroupMemberInfo(groupId, userId, true);

		String rawMessage = bot.getMsg(messageId).getRawMessage();
		if(userId!=BannedConstant.ADMINID){
			bot.sendGroupMsg(groupId, Msg.builder().at(userId).text("刚刚偷偷撤回的消息内容是:"+rawMessage), false);
		}
		return MESSAGE_IGNORE;
	}

	public static void main(String[] args) {
		System.out.println("http://s.music.qq.com/fcgi-bin/music_search_new_platform?t=0& n=5&aggr=1&cr=1&loginUin=0&format=json& inCharset=GB2312&outCharset=utf-8&notice=0& platform=jqminiframe.json&needNewCode=0&p=1&catZhida=0& remoteplace=sizer.newclient.next_song&w=".trim().replaceAll(" ",""));
	}


}
